<?php

//namespace lib;

if (!defined('BASEPATH')) exit('No direct script access allowed');

//注册自动加载方法
Base::register();

/**
 * 基础类库
 * @author feng.xiao
 */
class Base {

    public static $load;

    public function __construct() {
        // 实例化自己的 Loader 类
        $CI = & get_instance();
        self::$load = clone $CI->load;
    }

    //function Register()
    public static function register() {
        if (function_exists('__autoload')) {
            //    Register any existing autoloader function with SPL, so we don't get any clashes
            spl_autoload_register('__autoload');
        }
        //    Register ourselves with SPL
        return spl_autoload_register(array('Base', 'autoload'));
    }

    //自动加载类库
    public static function autoload($_className) {
        $classType = 'model';
//        if (class_exists($_className)) {
//            $res = $_className;
//        } else {
        if (stristr($_className, $classType)) {
            $res = self::loadModel($_className);
        } else {
            $res = self::loadLib($_className);
        }
//        }

        return $res;
    }

    //自动加载模型   
    public static function loadModel($_className) {
        return self::loadClass($_className, ['path' => MODELPATH, 'classType' => 'model']);
    }

    //自动加载类库
    public static function loadLib($_className) {
        return self::loadClass($_className, ['path' => LIBPATH, 'classType' => 'library']);
    }

    /**
     * 自动加载类方法
     * @param type $_className
     * @param type $type,数组['path' => LIBPATH, 'type' => 'library']
     * @return boolean
     */
    public static function loadClass($_className, $type) {
        $CI = & get_instance();
        if (isset(self::$load->$_className)) {
            return self::$load->$_className;
        } elseif (isset($CI->$_className)) {
            return $CI->$_className;
        } else {
            $fileName = $_className . '.php';
            foreach ([$fileName, strtolower($fileName)] as $v) {
                if (isset(self::$load->$_className)) {
                    return true;
                } else {
                    if (file_exists($type['path'] . $v)) {
                        $classType = $type['classType'];
                        self::$load->$classType($_className);
                        return true;
                    }
                }
            }
        }

        return false;
    }

}
